package com.kuang;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @program: kuang-redis
 * @description: redis事务
 * @author: 陈恩涛
 * @create: 2020-11-20 16:00
 **/
public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.43.58",6379);
        jedis.auth("123456");

        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","kuangshen");

        //开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();

        try {
            multi.set("user1",result);
            int i = 1/0;    //代码抛出异常，事务执行失败
            multi.set("user2",result);

            multi.exec();   //执行事务
        } catch (Exception e) {
            multi.discard();    //放弃事务
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();  //关闭连接
        }


    }
}
